﻿using Common.Communal;
using MediatR;
using Product.API.Read.Applications.Commands.ProductProcess;
using SqlSugar;

namespace Product.API.Read.Applications.CommandHandlers.ProductProcess
{
    /// <summary>
    /// 产品显示命令处理
    /// </summary>
    public class ProductCommandHandler : IRequestHandler<ProductCommand, ApiResult<ApiPaging<ERP.Domain.Products.Product>>>
    {
        /// <summary>
        /// SqlSugar
        /// </summary>
        private readonly ISqlSugarClient db;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="db">SqlSugar</param>
        public ProductCommandHandler(ISqlSugarClient db)
        {
            this.db = db;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public Task<ApiResult<ApiPaging<ERP.Domain.Products.Product>>> Handle(ProductCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<ERP.Domain.Products.Product>> result = new ApiResult<ApiPaging<ERP.Domain.Products.Product>>();
            result.Code = EnumCode.Ok;
            result.Message = EnumCode.Ok.ToString();

            int totalPage = 0;
            int totalCount = 0;
            var data = db.Queryable<ERP.Domain.Products.Product>().Where(x => x.IsDelete == false).ToPageList(request.pageIndex, request.pageSize, ref totalCount, ref totalPage);

            ApiPaging<ERP.Domain.Products.Product> page = new ApiPaging<ERP.Domain.Products.Product>();
            page.TotalCount = totalCount;
            page.TotalPage = totalPage;
            page.Data = data.ToList();
            result.Data = page;

            return Task.FromResult(result);
        }
    }
}
